using MediatR;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Menus.Commands.DeleteMenu;

public class DeleteMenuCommandHandler : IRequestHandler<DeleteMenuCommand, ApiResult<bool>>
{
  private readonly IUnitOfWork _uow;
  private readonly ILogger<DeleteMenuCommandHandler> _logger;

  public DeleteMenuCommandHandler(IUnitOfWork uow, ILogger<DeleteMenuCommandHandler> logger)
  {
    _uow = uow;
    _logger = logger;
  }

  public async Task<ApiResult<bool>> Handle(DeleteMenuCommand request, CancellationToken ct)
  {
    try
    {
      var menu = await _uow.MenuRepository.GetByIdAsync(request.Id);
      if (menu == null)
        return ApiResult<bool>.Failure(404, "菜单不存在");

      // 级联删除：EF Core 已配置 Cascade
      await _uow.MenuRepository.RemoveAsync(menu);
      await _uow.SaveChangesAsync();

      return ApiResult<bool>.Success(true, "删除成功");
    }
    catch (Exception ex)
    {
      _logger.LogError(ex, "删除菜单失败");
      return ApiResult<bool>.Failure(500, "服务器内部错误");
    }
  }
}